package com.woniuxy.cloud.userassembly.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.cloud.api.dto.RoleDto;
import com.woniuxy.cloud.dto.BaseDto;
import com.woniuxy.cloud.userassembly.dto.UsersSelRolesDto;
import com.woniuxy.cloud.userassembly.entity.Role;
import com.woniuxy.cloud.userassembly.entity.UserRole;
import com.woniuxy.cloud.userassembly.exception.RoleException;
import com.woniuxy.cloud.userassembly.mapper.RoleMapper;
import com.woniuxy.cloud.userassembly.param.BaseParam;
import com.woniuxy.cloud.userassembly.param.RolesPageAndByKeyParam;
import com.woniuxy.cloud.userassembly.param.SaveRoleParam;
import com.woniuxy.cloud.userassembly.param.UpdateRoleParam;
import com.woniuxy.cloud.userassembly.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.cloud.userassembly.service.UserRoleService;
import com.woniuxy.cloud.userassembly.util.PageMysqlUtil;
import com.woniuxy.cloud.userassembly.util.WoniuBeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 周川雄
 * @since 2022-01-26
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private UserRoleService urs;


    private ObjectMapper om = new ObjectMapper();

    /**
     * 分页模糊查询
     *
     * @param rp
     * @return
     */
    @Override
    public BaseDto<Role> listRoles(RolesPageAndByKeyParam rp) {
        QueryWrapper<Role> query = new QueryWrapper<>();
        if (!StringUtils.isEmpty(rp.getKey())) {
            query.and(wrapper -> wrapper
                    .like("role_name", rp.getKey())
                    .or()
                    .like("role_nickname", rp.getKey())
            );
        }
        query.eq("role_status", 0);

        return PageMysqlUtil.pageQuery(Role.class, this, query, new BaseParam(rp.getIndexPage(), rp.getPageSize()));

    }

    @Override
    public UsersSelRolesDto listRolesByUserId(Integer userId) {
        List<Role> list = list(new QueryWrapper<Role>().eq("role_status", 0));

        List<Integer> accountId = urs.list(new QueryWrapper<UserRole>().eq("user_id", userId))
                .stream().map(
                        ar -> ar.getRoleId()
                ).collect(Collectors.toList());
        UsersSelRolesDto dto = new UsersSelRolesDto();
        dto.setCheckedRoleIds(accountId);
        dto.setList(
                WoniuBeanUtils.copyList(list, RoleDto.class)
        );
        return dto;
    }

    @ExceptionHandler(Exception.class)
    @Override
    public boolean removeUserByIds(List<Integer> ids) {
        List<Role> roles = list(new QueryWrapper<Role>().eq("role_status", 0).in("role_id", ids));
        if (ids.size() != roles.size()) throw new RoleException("角色删除失败，请检查勾选角色", 10304);
        for (Role role : roles) {
            if (role.getRoleId() == 0) throw new RoleException("普通用户不能删除", 10308);
            role.setRoleStatus(1);
        }
        return updateBatchById(roles);
    }

    /**
     * 添加角色
     *
     * @param srp
     * @return
     */
    @ExceptionHandler(Exception.class)
    @Override
    public boolean SaveRole(SaveRoleParam srp) {
        QueryWrapper<Role> query = new QueryWrapper<>();
        //先判读是否有重名
        Role role = getOne(new QueryWrapper<Role>().eq("role_name", srp.getRoleName()));
        if (!StringUtils.isEmpty(role)) throw new RoleException("角色添加失败,该用户名已经存在", 10305);
        Role roleTable = WoniuBeanUtils.copyObject(srp, Role.class);
        roleTable.setRoleStatus(0);
        return save(roleTable);
    }

    @Override
    public RoleDto findRoleById(Integer roleId) throws JsonProcessingException {

        Role role = getOne(new QueryWrapper<Role>().eq("role_status", 0).eq("role_id", roleId));

        return WoniuBeanUtils.copyObject(role, RoleDto.class);


    }

    @Override
    public boolean updateRole(UpdateRoleParam urp) {
        //修改，修改只能修改备注
        Role roleTable = getOne(new QueryWrapper<Role>().eq("role_id", urp.getRoleId()).eq("role_status", 0));
        if (StringUtils.isEmpty(roleTable)) throw new RoleException("角色不存在", 10306);
        if (roleTable.getRoleId() == 0) throw new RoleException("普通用户不能删除", 10309);

        //同理要判断是否有重名
        if (!urp.getRoleName().isEmpty() || urp.getRoleName() != roleTable.getRoleName()) {
            Role role = getOne(new QueryWrapper<Role>().eq("role_name", urp.getRoleName()).ne("role_id", urp.getRoleId()));
            if (!StringUtils.isEmpty(role)) throw new RoleException("角色添加失败,该角色名已经存在", 10307);
        }
        return updateById(WoniuBeanUtils.copyObject(urp, Role.class));
    }
}
